package com.yupi.yupicturebackend.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.constant.UserConstant;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.manager.CosManger;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/file")
@Api(value = "文件接口")
public class FileController {
    @Resource
    private CosManger cosManger;

    @PostMapping("/test/upload")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "文件上传测试")
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipart) {
        String fileName = multipart.getOriginalFilename();
        String filePath = String.format("/test/%s", fileName);
        File file = null;
        try {
            file = File.createTempFile(filePath, null);
            multipart.transferTo(file);
            cosManger.putObject(filePath, file);
            return ResultUtils.success(filePath);
        } catch (Exception e) {
            log.error("file upload error, filePath = " + filePath,e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }finally {
            if (file != null) {
                boolean deleted = file.delete();
                if (!deleted) {
                    log.error("file delete error, filePath = " + filePath);
                }
            }
        }
    }
    @GetMapping("/test/download")
    @ApiOperation(value = "文件下载测试")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public void testFileDownLoad(String filePath, HttpServletResponse response) {
        // 获取文件流
        COSObjectInputStream cosObjectInput = null;
        try{
            // 获取文件对象
            COSObject cosObject = cosManger.getObject(filePath);
            // 获取文件流
            cosObjectInput = cosObject.getObjectContent();

            // 处理下载的文件流
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            response.setContentType("application/octet-stream");
            // 设置文件名
            response.setHeader("Content-Disposition", "attachment; filename=" + filePath);

            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("file download error ,filepath = {}", filePath);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        }finally {
            if (cosObjectInput != null) {
                try {
                    cosObjectInput.close();
                } catch (IOException e) {
                    log.error("file clos error ,filepath = {}", filePath);
                }
            }
        }
    }
}
